﻿using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Yyd.DocumentFilters
{
    public class SwaggerTagDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            if (swaggerDoc.Tags == null) swaggerDoc.Tags = new List<OpenApiTag>();

            //修改api的标签
            var allApiPath = swaggerDoc.Paths;
            foreach (var apis in allApiPath)
            {
                foreach (var opera in apis.Value.Operations)
                {
                    var apiTags = opera.Value.Tags;
                    if (!apiTags.IsNullOrEmpty())
                    {
                        foreach (var apiTag in apiTags)
                        {
                            var newTag = swaggerDoc.Tags.FirstOrDefault(f => f.Name == apiTag.Name);    //从tags中找到同一个controller

                            if (newTag != null && !newTag.Description.IsNullOrWhiteSpace())
                            {
                                apiTag.Name = newTag.Description;   //将接口中的tag改为中文描述
                            }
                        }
                    }
                }
            }

            //调换一下标签的名称和描述
            foreach (var item in swaggerDoc.Tags)
            {
                string oldDescrib = item.Name;
                item.Name = item.Description;
                item.Description = oldDescrib;
            }


            //--------------开启下列代码，可变更swagger文档，方便导入apiPost
            //var newPaths = new OpenApiPaths();

            //foreach (var item in swaggerDoc.Paths)
            //{
            //    var newPath = item.Key;
            //    foreach (var operation in item.Value.Operations)
            //    {
            //        var method = operation.Key.ToString().ToLower();
            //        newPath = $"{newPath}/{method}";
            //    }
            //    //@"/\{[^/]+\}" 
            //    //  ^/+[^/]+/? 去除形如////2222/ /222/
            //    newPath = System.Text.RegularExpressions.Regex.Replace(newPath, "/api/", "/").ToLower();
            //    newPaths.Add(newPath, item.Value);
            //}
            //swaggerDoc.Paths = newPaths;

        }
    }
}
